package com.srit.identify.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.srit.identify.common.SocketNet;
import com.srit.identify.common.utils.SocketUtil;
import com.srit.identify.dao.GoodsInfoDao;
import com.srit.identify.entity.GoodsInfo;
import com.srit.identify.entity.IdentifyInfo;
import com.srit.identify.service.IIdentifyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class IdentifyServiceImpl implements IIdentifyService {
    @Resource
    private SocketNet socketNet;

    @Resource
    private GoodsInfoDao goodsInfoDao;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public Object identify(IdentifyInfo identifyInfo) {
        try {
            lock.lock();
            OutputStream os = socketNet.getOutputStream();
            byte[] send = SocketUtil.getBytes(JSON.toJSONString(identifyInfo));
            System.out.println(send.length);
            os.write(send);
            os.flush();
            StringBuilder builder = new StringBuilder("send to  ===>  [");
            for (int i = 0; i < 20; i++) {
                builder.append(send[i]).append(",");
            }
            builder.append(".......");
            for (int i = send.length - 20; i < send.length; i++) {
                builder.append(send[i]).append(",");
            }
            builder.append("]");
            System.out.println(builder.toString());
            InputStream is = socketNet.getInputStream();
            int available = 0;
            long start = System.currentTimeMillis();
            while ((available = is.available() ) == 0){
                if ((System.currentTimeMillis() - start) > 3000 ) return null;
            }
            byte[] bytes = new byte[available];
            int read = is.read(bytes);
            System.out.println("back <====" + Arrays.toString(bytes));
            JSONObject re = SocketUtil.parseBytes(bytes);
            String classifyCode = re.getString("classifyCode");
            GoodsInfo byId = goodsInfoDao.getById(classifyCode);
            re.put("classifyName", byId.getName());
            return re;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return null;

    }
}
